#{include file="../Common/Header.html"}
<div class="layui-container fly-marginTop fly-user-main">
    #{include file="../Common/Nav.html"}
    <div class="fly-panel fly-panel-user" pad20>
        <div class="layui-tab layui-tab-brief" lay-filter="user">
            <div class="content-header">
                <i class="layui-icon">&#xe638;</i> 卡密管理
            </div>

            <div class="content-body">
                <div style="margin-bottom: 5px;margin-top: 15px;">
                    <button type="button" class="layui-btn layui-btn-sm layui-btn-pink button-add"><i class="layui-icon"
                                                                                                      style="position: relative;top: -2px;">&#xe624;</i>上传卡密
                    </button>
                    <button type="button" class="layui-btn layui-btn-sm layui-btn-pink button-del"><i class="layui-icon"
                                                                                                      style="position: relative;top: -2px;">&#xe640;</i>移除选中卡密
                    </button>

                    <button type="button" class="layui-btn layui-btn-sm layui-btn-pink button-lock"><i
                                class="layui-icon"
                                style="position: relative;top: -2px;">&#xe673;</i>锁定选中卡密
                    </button>

                    <button type="button" class="layui-btn layui-btn-sm layui-btn-pink button-unlock"><i
                                class="layui-icon"
                                style="position: relative;top: -2px;">&#xe672;</i>解锁选中卡密
                    </button>
                    <button type="button" class="layui-btn layui-btn-sm layui-btn-pink button-export"><i
                                class="layui-icon"
                                style="position: relative;top: -2px;">&#xe67d;</i>导出筛选卡密
                    </button>
                </div>
                <form class="search-query"></form>

                <table id="user-card" lay-filter="user-card"></table>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        layui.use(['hex', 'form'], function () {
            let table = $("#user-card");
            let cao = layui.hex;
            let form = layui.form;
            let status = ['<span class="acg-badge acg-badge-light-red">未出售</span>', '<span class="acg-badge acg-badge-light-success">已出售</span>', '<span class="acg-badge acg-badge-light">锁定</span>'];

            var _commodity;
            let commodity = function () {
                if (!_commodity) {
                    _commodity = User.$postSync("/user/api/commodity/data", {limit: 1000, page: 1});
                }
                let dict = [];
                _commodity.forEach(item => {
                    dict.push({id: item.id, name: item.name});
                })
                return dict;
            }

            let queryParams = null;
            table.bootstrapTable({
                url: '/user/api/card/data',//请求的url地址
                method: "post",//请求方式
                pageSize: 6,//每页显示的数量
                showRefresh: false,//是否显示刷新按钮
                cache: false,//是否使用缓存
                showToggle: false,//是否显示详细视图和列表视图的切换按钮
                cardView: false,
                pagination: true,//是否显示分页
                pageNumber: 1,//初始化显示第几页，默认第1页
                singleSelect: false,//复选框只能选择一条记录
                sidePagination: 'server',//分页显示方式，可以选择客户端和服务端（server|client）
                contentType: "application/x-www-form-urlencoded",//使用post请求时必须加上
                dataType: "json",//接收的数据类型
                queryParamsType: 'limit',//参数格式，发送标准的Restful类型的请求
                queryParams: function (params) {
                    params.page = (params.offset / params.limit) + 1;
                    if (queryParams) {
                        for (const key in params) {
                            queryParams[key] = params[key];
                        }
                    } else {
                        queryParams = params;
                    }
                    return queryParams;
                },
                //回调函数
                responseHandler: function (res) {
                    return {
                        "total": res.count,
                        "rows": res.data
                    }
                },
                columns: [
                    {checkbox: true}
                    , {
                        field: 'secret', title: '卡密信息', formatter: function (val, item) {
                            return '<span class="acg-badge acg-badge-light">' + item.secret + '</span>';
                        }, width: 160
                    }
                    , {
                        field: 'commodity', title: '商品', formatter: function (val, item) {
                            if (!item.commodity) {
                                return "-";
                            }
                            return item.commodity.name;

                        }
                    }
                    , {
                        field: 'race', title: '类别', formatter: function (val, item) {
                            if (!item.race) {
                                return "-";
                            }
                            return item.race;
                        }
                    }
                    , {field: 'create_time', title: '创建时间'}
                    , {field: 'note', title: '备注信息'}
                    , {
                        field: 'status', title: '状态', formatter: function (val, item) {
                            return status[item.status];
                        }
                    }
                    , {
                        field: 'purchase_time', title: '出售时间', formatter: function (val, item) {
                            if (!item.purchase_time) {
                                return '-';
                            }
                            return item.purchase_time;
                        }
                    }
                    , {
                        field: 'operate',
                        title: '',
                        formatter: function (val, item) {
                            let html = '';
                            if (item.status == 0) {
                                html += '<span type="button" data-id="' + item.id + '" class="acg-badge-button acg-badge acg-badge-light-primary lock"><i class="layui-icon">&#xe673;</i> 锁定</span> ';
                            } else if (item.status == 2) {
                                html += '<span type="button" data-id="' + item.id + '" class="acg-badge-button acg-badge acg-badge-light-success unlock"><i class="layui-icon">&#xe672;</i> 解锁</span> ';
                            }
                            html += '<span type="button" data-id="' + item.id + '" class="acg-badge-button acg-badge acg-badge-light-red del"><i class="layui-icon">&#xe640;</i> 删除</span> ';
                            return html;
                        },
                        events: {
                            'click .del': function (event, value, row, index) {
                                layer.confirm('您是否要移除该卡密，这是无法恢复的？', {
                                    btn: ['确认移除', '取消']
                                }, function () {
                                    $.post('/user/api/card/del', {list: [row.id]}, res => {
                                        layer.msg(res.msg);
                                        table.bootstrapTable('refresh', {silent: true});
                                    });
                                });
                            },
                            'click .unlock': function (event, value, row, index) {
                                $.post('/user/api/card/unlock', {list: [row.id]}, res => {
                                    layer.msg(res.msg);
                                    table.bootstrapTable('refresh', {silent: true});
                                });
                            },
                            'click .lock': function (event, value, row, index) {
                                $.post('/user/api/card/lock', {list: [row.id]}, res => {
                                    layer.msg(res.msg);
                                    table.bootstrapTable('refresh', {silent: true});
                                });
                            }
                        }
                    }
                ]
            });

            let modal = (values = {}) => {
                cao.popup('/user/api/card/save', [
                    {
                        title: "选择商品",
                        name: "commodity_id",
                        type: "select",
                        dict: commodity(),
                        placeholder: "请选择商品",
                        search: true
                    },
                    {
                        title: "商品类别",
                        name: "race",
                        type: "input",
                        placeholder: "商品类别，一般你用不着，而且不懂不要乱填哦，想用请查看说明文档"
                    },
                    {
                        title: "备注信息",
                        name: "note",
                        type: "input",
                        placeholder: "备注信息(可空)，方便查询某次添加的卡密"
                    },
                    {
                        title: "卡密信息",
                        name: "secret",
                        type: "textarea",
                        placeholder: "卡密信息+预选信息（多个），一行即算一个卡密信息+预选信息\n\n" +
                            "例子1（游戏账号+预选信息）：\n大区:神境之地----等级:100----ID:逆天而行----觉醒:已觉醒----段位:无人之境----账号:admin----密码:123456#[大区:神境之地----等级:100----ID:逆天而行----觉醒:已觉醒----段位:无人之境]#\n\n" +
                            "例子2（卡密信息+无预选）：\nAAKvSsfWGnFdnqP\nf5V61wpeAIuX35t\n1a9Xn35qsEQwp32\n\n提示：#[我是预选信息内容]#，预选信息代表买家在购买的时候可以通过加价的方式预选自己想购买的卡密信息，一般用作与购买自己想要的账号等",
                        height: 420
                    },
                    {
                        title: "",
                        name: "explain",
                        type: "explain",
                        placeholder: '<input class="draft-input" style="border:1px solid #fdabe678;border-radius: 5px;padding:5px;" type="text" placeholder="预选卡密隐藏正则，可不填"><button type="button" style="border: none;margin-left: 5px;padding: 2px 5px 2px 5px;background: #fd6ace96;border-radius: 5px;color: whitesmoke;cursor:pointer;" class="draft-btn">处理</button>'
                    },
                    {
                        title: "去除重复",
                        name: "unique",
                        type: "switch",
                        text: "启用（保持数据唯一）"
                    },
                ], res => {
                    table.bootstrapTable('refresh', {silent: true});
                }, values, ["660px", "820px"], false, "添加", unqueId => {
                    $('.draft-btn').click(function () {
                        let regx = $('.draft-input').val();
                        let cards = cao.popupElement("secret", "textarea", unqueId).val().trim();
                        let newCards = "";
                        let success = 0;
                        let error = 0;
                        cards.split('\n').forEach(item => {
                            item = item.trim();
                            if (/#\[(.*?)\]#/.test(item)) {
                                newCards += item + "\n";
                                error++;
                            } else {
                                newCards += item + '#[' + item.replace(eval("/" + regx + "/i"), "") + ']#\n';
                                success++;
                            }
                        });
                        cao.popupElement("secret", "textarea", unqueId).val(newCards.trim());
                        layer.msg("预选卡密处理完成，已处理：" + success + "，未处理：" + error);
                    });
                });
            }

            $('.button-add').click(function () {
                modal();
            });

            $('.button-del').click(() => {
                let data = cao.listObjectToArray(table.bootstrapTable('getSelections'));
                if (data.length == 0) {
                    layer.msg("请至少勾选1个卡密再进行操作！");
                    return;
                }
                layer.confirm('您确定要删除已经选中的卡密吗？这是不可恢复的操作！', {
                    btn: ['确定', '取消']
                }, function () {
                    $.post("/user/api/card/del", {list: data}, res => {
                        layer.msg(res.msg);
                        table.bootstrapTable('refresh', {silent: true});
                    });
                });
            });

            $('.button-lock').click(() => {
                let data = cao.listObjectToArray(table.bootstrapTable('getSelections'));
                if (data.length == 0) {
                    layer.msg("请至少勾选1个卡密进行操作！");
                    return;
                }
                layer.confirm('您确定要锁定选中的卡密吗？', {
                    btn: ['确定', '取消']
                }, function () {
                    $.post("/user/api/card/lock", {list: data}, res => {
                        layer.msg(res.msg);
                        table.bootstrapTable('refresh', {silent: true});
                    });
                });
            });

            $('.button-unlock').click(() => {
                let data = cao.listObjectToArray(table.bootstrapTable('getSelections'));
                if (data.length == 0) {
                    layer.msg("请至少勾选1个卡密进行操作！");
                    return;
                }
                layer.confirm('您确定要解锁选中的卡密吗？', {
                    btn: ['确定', '取消']
                }, function () {
                    $.post("/user/api/card/unlock", {list: data}, res => {
                        layer.msg(res.msg);
                        table.bootstrapTable('refresh', {silent: true});
                    });
                });
            });

            $('.button-export').click(function () {
                layer.open({
                    type: 1,
                    shade: 0.3,
                    content: '<form class="layui-form" action="">\n' +
                        '    <div style="margin-top: 10px;margin-left: 20px;">\n' +
                        '      <input type="radio" name="export_status" value="0" title="不操作" checked>\n' +
                        '      <input type="radio" name="export_status" value="1" title="锁定卡密">\n' +
                        '      <input type="radio" name="export_status" value="2" title="删除卡密">\n' +
                        '    </div>\n' +
                        '</form>',
                    title: "导出后，你还想做什么？（・ω・）",
                    btn: ['确认', '取消'],
                    shadeClose: true,
                    yes: (index, layero) => {
                        layer.close(index);
                        let exportStatus = $(".layui-form input[name=export_status]:checked").val();
                        let query = $('.search-query').serialize();
                        window.open('/user/api/card/export?exportStatus=' + exportStatus + "&" + query);
                    },
                    success: (layero, index) => {
                        form.render();
                    }
                });
            });

            cao.query('.search-query', table, [
                {title: "卡密信息(精确搜索,速度快)", name: "equal-secret", type: "input"},
                {title: "卡密信息(模糊搜索,速度慢)", name: "search-secret", type: "input"},
                {title: "备注信息", name: "equal-note", type: "input"},
                {
                    title: "状态", name: "equal-status", type: "select", dict: [
                        {id: 0, name: "未出售"},
                        {id: 1, name: "已出售"},
                        {id: 2, name: "锁定"},
                    ]
                },
                {title: "商品ID", name: "equal-commodity_id", type: "input"},
                {title: "入库时间从", name: "betweenStart-create_time", type: "date"},
                {title: "到入库时间", name: "betweenEnd-create_time", type: "date"},
            ], true, false);
        });
    });
</script>
#{include file="../Common/Footer.html"}
